package org.hank.compose_yyzs.http

import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import okhttp3.Interceptor
import okhttp3.Response
import org.hank.compose_yyzs.constants.Constants

/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/3/17 18:12
 *描述:
 */
class TokenInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        val originalRequest = chain.request()

        // 获取保存在本地的token
        val token = MMKV.defaultMMKV()!!.getString(Constants.TOKEN, "")
//        Logger.d("token======= $token")
        // 如果token存在，则将其添加到Cookie中
        val newRequest = if (token!!.isNotEmpty()) {
            originalRequest.newBuilder()
                .addHeader("Authorization", "Bearer $token")
                .build()
        } else {
            originalRequest
        }

        return chain.proceed(newRequest)
    }
}